from socket import*
import random
from datetime import*

def main(server_port):
    #1. 启动服务器端,创建UDP套接字
    server_socket = socket(AF_INET, SOCK_DGRAM)
    server_socket.bind(('', server_port))
    print("服务器已启动。")

    #2. 模拟TCP连接建立
    message, client_address = server_socket.recvfrom(2048)
    if message.decode()=='SYN':
        print("从client端接收到"+message.decode()+",发送server ACK")  # 输出检测
        server_socket.sendto('SYN-ACK'.encode(),client_address)
        message, client_address = server_socket.recvfrom(2048)
        if message.decode() == 'ACK':
            print("成功建立连接")
        else:
            print("连接建立失败, socket close")
            server_socket.close()
            return

    #3. 开始接收数据报
    while True:
        message, client_address = server_socket.recvfrom(2048)
        # print(message.decode())
        # 连接释放消息
        if(message.decode()=="FIN1"):
            break

        client_no=message[:2].decode()
        ver=message[2:3].decode()
        print(f"packet{client_no} accept!")

        # 响应：
        if random.random() >= 0.5:  #丢包率设置为50%
            print(f"packet{client_no}:模拟丢包")
            continue
        else:
            curr_time = datetime.now().strftime("%H-%M-%S")
            message=f"{client_no}{ver}{curr_time}"
            server_socket.sendto(message.encode(), client_address)

    #模拟连接断开-
    server_socket.sendto('server ACK'.encode(), client_address)
    server_socket.sendto('FIN2'.encode(), client_address)
    message ,client_address = server_socket.recvfrom(2048)
    if message.decode() == 'client ACK':
        server_socket.close()
        print("成功断开连接！")
    else:
        print("断开连接失败：未接收到client ACK")


if __name__ == "__main__":
    server_port = 12345  # 服务器端口
    main(server_port)